import type { ProColumns } from '@ant-design/pro-components';
import {
  EditableProTable,
  ProCard,
  ProFormField,
  ProFormRadio,
} from '@ant-design/pro-components';
import { message, Modal ,Popconfirm} from 'antd';
import React, { useState, useEffect } from 'react';
import  { flushSync } from 'react-dom';
import { GetActivity , PatchActivity, DeleteActivity, PostActivity} from '@/api/home'
import { genPreviewOperationsStyle } from 'antd/lib/image/style';
import { useModel } from 'umi';
// type DataSourceType = {
//   id: React.Key;
//   title?: string;
//   readonly?: string;
//   decs?: string;
//   state?: string;
//   created_at?: number;
//   update_at?: number;
//   children?: DataSourceType[];
// };

// const defaultData: DataSourceType[] = [
//   {
//     id: 624748504,
//     title: '活动名称一',
//     readonly: '活动名称一',
//     decs: '这个活动真好玩',
//     state: 'open',
//     created_at: 1590486176000,
//     update_at: 1590486176000,
//   },
//   {
//     id: 624691229,
//     title: '活动名称二',
//     readonly: '活动名称二',
//     decs: '这个活动真好玩',
//     state: 'closed',
//     created_at: 1590481162000,
//     update_at: 1590481162000,
//   },
// ];
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('执行了')
      resolve(true);
    }, time);
  });
};

export default () => {
  const { initialState, setInitialState } = useModel('@@initialState'); // 获取State持久化数据
  const userId = initialState.currentUser.userinfo.id
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState([]);
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>(
    'bottom',
  );
  const [logo,setLogo] = useState([true])
  // 获取活动列表 数据
  const GetData = async () => {
    const data = await GetActivity(1,20)
    console.log("data--------",data)
    // console.log('Activity-data', data.results[0].user.username)

    // 将data数据展平 
    const flattenedDataSource = data.results.map(item => ({  
      ...item,  
      username: item.user ? item.user.username : null, // 将username提升到顶级  
      // ... 其他需要提升的字段  
    }));
    setDataSource(flattenedDataSource)
  };
  // 添加数据
  const AddData = async (options) => {
    try{
      delete options.id
      options.user_id = userId
      console.log("options",options)
      // options.
      const data = await PostActivity(options)
      // 将data数据展平 
      // 将data数据展平 
      const flattenedDataSource = {  ...data,  username: data.user ? data.user.username : null}
      setDataSource([...dataSource,flattenedDataSource])
      // console.log("2",)
      message.success("添加成功")
    } catch(err){
      console.log(err)
    }
  }
  // 保存 Onsave
  const PatchData = async (uid,options) => {
    try{
      // console.log("--options",options)
       const {status,activity_name,activity_description,start_date,end_date,venue,participant_count} = options
      //  console.log({status})
       const data = await PatchActivity(uid,{status,activity_name,activity_description,start_date,end_date,venue,participant_count})
      //  GetData() //暂时利用get 获取数据

       // 将data数据展平 
       const flattenedDataSource = dataSource.map(item => {  
        // console.log(item.id,"----",uid)
        if(item.id === uid){
          return {...data,username: item.user ? item.user.username : null}
        }
        return item
       });
       flushSync(setLogo(true))
       setDataSource(flattenedDataSource)
       message.success("修改成功！")
    } catch(err){
      console.log(err)
      message.error("修改失败！")
      flushSync(setLogo(false))
      
      // setLogo(false)
    }
    // console.log('保存了')
  }
  const ChangeFC =(val) =>{
    console.log("改变",logo)
    // setDataSource001(val)
  }
  // 组件初始化 时候运行
  useEffect(() => {
    GetData();
  }, []); // 空数组作为第二个参数，表示只在组件加载时运行一次
  //判断
  const hasOnlyIdAndIndex = (obj) => {  
    const keys = Object.keys(obj);  
    return keys.length === 2 && keys.includes('id') && keys.includes('index');  
  }  

  //   console.log(dataSource)
  const columns = [
    {
      title: 'UID',
      dataIndex: 'id',
      readonly: true,  // 是否禁用状态
      tooltip: '只读',
    },
    {
      title: '用户',
      dataIndex: 'username',
      readonly: true,  // 是否禁用状态
      tooltip: '只读',
      //   formItemProps: (form, { rowIndex }) => {
      //     return {
      //       rules:
      //         rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
      //     };
      //   },
      //   // 第一行不允许编辑
      //   editable: (text, record, index) => {
      //     return index !== 0;
      //   },
      //   width: '10%',
    },
    {
      title: '名称',
      dataIndex: 'activity_name',
      // readonly: true,  // 是否禁用状态 
        // width: '15%',
      formItemProps: (form, { rowIndex }) => {
          return {
            rules:
              rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
          };
        },
    },
    {
      title: '活动描述',
      dataIndex: 'activity_description',
      fieldProps: (form, { rowKey, rowIndex }) => {
        if (form.getFieldValue([rowKey || '', 'title']) === '不好玩') {
          return {
            disabled: true,
          };
        }
        if (rowIndex > 9) {
          return {
            disabled: true,
          };
        }
        return {};
      },
    },
    {
      title: '开始时间',
      dataIndex: 'start_date',
      valueType: 'date',
    },
    {
      title: '结束时间',
      dataIndex: 'end_date',
      valueType: 'date',
    },
    {
      title: '人数',
      dataIndex: 'participant_count',
      // valueType: 'date',
    },
    {
      title: '地点',
      dataIndex: 'venue',
      // valueType: 'date',
    },
    {
      title: '状态',
      // key: 'id',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        '0': { text: '草稿', status: 'Default' },
        '1': { text: '提交', status: 'Warning' },
        '2': { text: '同意', status: 'Success', },
        '3': { text: '拒绝', status: 'Error', },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        // <a
        //   key="delete"
        //   onClick={() => {
        //     // handleConfirm();
        //     Modal.confirm({
        //       title: '确认删除',
        //       content: '确定要删除这条记录吗？',
        //       onOk: () => {
        //         // 确认删除逻辑
        //         setDataSource(dataSource.filter((item) => item.id !== record.id));
        //       },
        //     });
        //   }}
        // >
        //   删除
        // </a>,
        <Popconfirm
          key="delete"
          title="确定要删除这条记录吗？"
          onConfirm={() => {
            // 确认删除逻辑
            setDataSource(dataSource.filter((item) => item.id !== record.id));
            message.success('删除成功');
          }}
          onCancel={() => {
            message.info('取消删除');
          }}
          okText="确认"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <>
      <EditableProTable
        rowKey="id"
        headerTitle="可编辑表格"
        // maxLength={10} // ???
        scroll={{
          x: 960,
        }}
        recordCreatorProps={
          position !== 'hidden'
            ? {
              position: position as 'top',
              record: () => ({ id: (Math.random() * 1000000).toFixed(0) }), // 默认生成 随机的id
            }
            : false
        }
        loading={false}
        toolBarRender={() => [
          <ProFormRadio.Group
            key="render"
            fieldProps={{
              value: position,
              onChange: (e) => setPosition(e.target.value),
            }}
            options={[
              {
                label: '添加到顶部',
                value: 'top',
              },
              {
                label: '添加到底部',
                value: 'bottom',
              },
              //   {
              //     label: '隐藏',
              //     value: 'hidden',
              //   },
            ]}
          />,
        ]}
        columns={columns}
        // request={async () => ({
        //   data: defaultData, // 将数据给dataSource 数据
        //   total: 3,
        //   success: true,
        // })}
        value={dataSource}
        onChange={ChangeFC}
        editable={{
          
          type: 'multiple',
          editableKeys,
          //   点击保存时候触发
          onSave: async (rowKey, data, row) => {
            // console.log('id???', rowKey)
            console.log( "---data",data);
            console.log( "---row",row);
            if (hasOnlyIdAndIndex(row)) {  
              // 处理只有id和index的情况  
              AddData(data)
              // message.error("添加失败")
              return
              // return <div>Object has only id and index</div>;  
            } 
            PatchData(rowKey,data)
            await waitTime(1000);
            // message.info('已保存修改');
          },
          //   点击删除
          onChange: setEditableRowKeys,
          // 点击取消
          onCancel: () => {
            message.info('已取消编辑');
          },
        }}
      />

      {/* 表格JSON数据 */}
      <ProCard title="表格数据" headerBordered collapsible defaultCollapsed>
        <ProFormField
          ignoreFormItem
          fieldProps={{
            style: {
              width: '100%',
            },
          }}
          mode="read"
          valueType="jsonCode"
          text={JSON.stringify(dataSource)}
        />
      </ProCard>
    </>
  );
};